<?php
/**
 * Created by PhpStorm.
 * User: Sojo
 * Date: 2017/6/20
 * Time: 19:34
 */
namespace App\Api\Service\Test\Models;

use Framework\BaseClass\Api\Model;

class Contacts extends Model
{
    private $returnStr = '';
    private $contacts_count = 0;

    /**
     * 获取通讯录数据
     * @author Sojo
     * @param $userId
     * @return string
     */
    public function getContactsData($userId)
    {
        $contacts = '{"versions":"0","allUser":[';

        if (!$userId) {
            exit('userId is null');
            $contacts .= $this->printoutContacts([]);
            $contacts .= "]}";

            $content = $contacts;

            return $content;
        }

        // 根据用户ID获取该公司ID
        $ownerEmployeeInfo = Employee::with('ownerInfo')->where('user_id', $userId)->first();
//        $owner = $ownerEmployeeInfo->ownerInfo;
//        if (!$ownerEmployeeInfo || empty($owner)) {
        // @author lulingfeng 2017.8.30 owner赋值放到下面，防止$ownerEmployeeInfo空对象错误  --start
        if (!$ownerEmployeeInfo || empty($ownerEmployeeInfo->ownerInfo)) {
            exit('ownerEmployeeInfo is null');
            $contacts .= $this->printoutContacts([]);
            $contacts .= "]}";

            $content = $contacts;

            return $content;
        }
        $owner = $ownerEmployeeInfo->ownerInfo;
        // @author lulingfeng 2017.8.30 owner赋值放到下面，防止$ownerEmployeeInfo空对象错误  --end

        // 根据公司ID，获取该公司通讯录内有多少员工
        $ownerEmployeeList = Employee::with('userInfo')->where('owner_id', $owner->id)->limit(10)->orderBy('updated_at', 'desc')->get();
        $ownerEmployeeNumber = $ownerEmployeeList->count();

        // 获取该公司下最新修改过信息的时间戳
        $newUpdateTime = $ownerEmployeeList->first()->updated_at->timestamp;


        // 版本号由公司总员工数 + 最新修改的时间戳 - 配合APP，版本号减去10亿
        $version = abs($ownerEmployeeNumber + $newUpdateTime - 1000000000);

        //版本号，用来让手机判断是否需要更新通讯录
        $contacts = '{"versions":"' . $version . '","allUser":[';

        // 数据拼装
        $owner->cat_name = $owner->name;

        $category_tree[$owner->id] = ['main' => $owner->toArray(), 'sub' => [], 'people' => []];
        foreach ($ownerEmployeeList as $ownerEmployee) {
            $name_rand      = $this->getChar(3);
            $ownerEmployee->contact_name = isset($ownerEmployee->userInfo->name) ? $ownerEmployee->userInfo->name : $name_rand;
            $ownerEmployee->email = isset($ownerEmployee->userInfo->email) ? $ownerEmployee->userInfo->email : '';
            $ownerEmployee->job = $ownerEmployee->department . '-' . $ownerEmployee->job_title;
            $ownerEmployee->mobile = !empty($ownerEmployee->userInfo->mobile_phone)
                ? $ownerEmployee->userInfo->mobile_phone
                : $ownerEmployee->work_phone;
            $ownerEmployee->tel = '';
            $ownerEmployee->shorttel = '';
//            $ownerEmployee->avatar = '';
            // @author lulingfeng 2017.9.13 添加头像   start-----
            $ownerEmployee->avatar = empty($ownerEmployee->userInfo->avatar_url) ? '' : env('APP_URL') . $ownerEmployee->userInfo->avatar_url;
            // @author lulingfeng 2017.9.13 添加头像   end-------

            $category_tree[$owner->id]['people'][] = $ownerEmployee->toArray();
        }

        $contacts .= $this->printoutContacts($category_tree);
        $contacts .= "]}";

        return $contacts;
    }
    public function getChar($num)  // $num为生成汉字的数量
    {
        $str_xing           = [
            '赵','钱','孙','李','周','吴','郑','王',
            '冯','陈','褚','卫','蒋','沈','韩','杨',
            '朱','秦','尤','许','何','吕','施','张',
        ];
        $str_ming           = [
            '筠','柔','竹','霭','凝','晓','欢','霄','枫','芸','菲','寒','伊','亚','宜',
            '可','姬','舒','影','荔','枝','思','丽','秀','娟','英','华','慧','巧','美',
            '娜','静','淑','惠','珠','翠','雅','芝','玉','萍','红','娥','玲','芬','芳',
            '燕','彩','春','菊','勤','珍','贞','莉','兰','凤','洁','梅','琳','素','云',
            '莲','真','环','雪','荣','爱','妹','霞','香','月','莺','媛',' 艳','瑞','凡',
            '佳','嘉','琼','桂','娣','叶','璧','璐','娅','琦','晶','妍','茜','秋','珊',
            '莎','锦','黛','青','倩','婷','姣','婉','娴','瑾','颖','露','瑶','怡','婵',
            '雁','蓓','纨','仪','荷','丹','蓉','眉','君','琴','蕊','薇','菁','梦','岚',
            ' 苑','婕','馨','瑗','琰','韵','融','园','艺','咏','卿','聪','澜','纯','毓',
            '悦','昭','冰','爽','琬','茗','羽','希','宁','欣','飘','育'
        ];
        $str_xing_size      = count( $str_xing );
        $str_xing_size      = $str_xing_size - 1;
        $str_ming_size      = count( $str_ming );
        $str_ming_size      = $str_ming_size - 1;
        $xing               = mt_rand( 1, $str_xing_size );
        $ming               = mt_rand( 1, $str_ming_size );
        $ming2              = mt_rand( 1, $str_ming_size );
        $name               = $str_xing[$xing].$str_ming[$ming].$str_ming[$ming2];
        return $name;
    }
    /**
     * 递归处理通讯录数据
     * @author Sojo
     * @param $tree
     * @return string
     */
    private function getContactsRecursive($tree)
    {
        if (count($tree['sub']) > 0) { //如果有子部门，继续往下找
            $this->returnStr .= '{"' . $tree['main']['cat_name'] . '":[';
            for ($i = 0; $i < count($tree['sub']); $i++) {
                $this->returnStr .= $this->getContactsRecursive($tree['sub'][$i]);
            }
            if (count($tree['sub']) > 0)
                $this->returnStr = substr($this->returnStr, 0, -1);
            $this->returnStr .= ']},';
        } else { //如果没有子部门了，就找这个部门里的所有人员
            $this->returnStr .= '{"' . $tree['main']['cat_name'] . '":[';
            for ($i = 0; $i < count($tree['people']); $i++) {
                $this->contacts_count++;
                $gbkname = iconv('UTF-8', 'GBK', $tree['people'][$i]['contact_name']); //这里utf-8转GBK的用意是，转拼音的那个函数需要GBK
                $gbkname = str_replace(" ", "", $gbkname);

                require_once dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/framework/Extend/Helpers/pinyin/pinyin.php';

                $flow = get_pinyin_array($gbkname);
                $shortSpellArr = explode("_", $flow[0]);
                $shortSpell = "";
                for ($s = 1; $s < count($shortSpellArr) - 1; $s++) {
                    $shortSpell .= strtoupper(substr($shortSpellArr[$s], 0, 1));
                }
                $tree['people'][$i]['longspell'] = iconv('GBK', 'UTF-8', str_replace("_", "", $flow[0])); //拼音获得后再转回utf-8
                $tree['people'][$i]['shortspell'] = iconv('GBK', 'UTF-8', $shortSpell);
                $this->returnStr .= sprintf('{"id":"%d","username":"%s","email":"%s","title":"%s","workCellPhone":"%5$s","personalCellPhone":"","workingPhone":"%6$s","homePhone":"","shortNum":"%7$s","pinyin":["%8$s"],"firstPinyin":["%9$s"],"avatar":"%10$s"},', $tree['people'][$i]['id'], $tree['people'][$i]['contact_name'], $tree['people'][$i]['email'], $tree['people'][$i]['job'], $tree['people'][$i]['mobile'], $tree['people'][$i]['tel'], $tree['people'][$i]['shorttel'], $tree['people'][$i]['longspell'], $tree['people'][$i]['shortspell'], $tree['people'][$i]['avatar']);
            }
            if (count($tree['people']) > 0)
                $this->returnStr = substr($this->returnStr, 0, -1);

            $this->returnStr .= ']},';
            return $this->returnStr;
        }
        return $this->returnStr;
    }

    /**
     * 输出通讯录返回数据
     * @author Sojo
     * @param $tree
     * @return string
     */
    private function printoutContacts($tree)
    {
        $contactStr = "";
        foreach ($tree as $item) {
            $contactStr .= $this->getContactsRecursive($item);
        }
        $contactStr = substr($contactStr, 0, -1);

        return $contactStr;
    }
}